import { ref, computed } from 'vue'
import { defineStore } from 'pinia'

export const userInfoStore = defineStore('userInfo', () => {
  const userString = ref(localStorage.getItem("userInfo") || null)
  const userDict = computed(()=> userString.value? JSON.parse(userString.value):null)
  const userName = computed(()=> userDict.value? userDict.value.username:null)
  const userToken = computed(()=> userDict.value? userDict.value.token:null)
  const userPermission = computed(()=> userDict.value? userDict.value.permission:null)
  const userMenu = computed(()=> userDict.value? userDict.value.menu:null)
  const userMenuNameList = computed(()=> {
    let result = []
    for (let key in userDict.value.menu){

      for (let idx in userDict.value.menu[key]['children']){
        let row_dict = userDict.value.menu[key]['children'][idx]
        result.push(row_dict.name)
      }
    }
    return result

  })
  function doLogin(info){
    localStorage.setItem("userInfo",JSON.stringify(info))
    userString.value = JSON.stringify((info))
  }
  function doLogout(){
    userString.value= null
    localStorage.removeItem("userInfo")
  }

  return {userName,userToken,userPermission,userMenu,userMenuNameList,doLogin,doLogout}
})
